<?php
/**
 * Created by PhpStorm.
 * User: bevan
 * Date: 2018/1/2
 * Time: 下午3:10
 */

namespace thans\auth\model;

use think\Model;

class AuthGroupModel extends Model
{

    /**
     * 所有的权限组
     * @return mixed
     */
    public function getAllUserGroup($keyword)
    {
        if($keyword == ''){
            $all_groups =  self::all();
        }else{
            $all_groups = self::where('title','like','%'.$keyword.'%')->select();
        }

        return $all_groups;
    }

    /**
     *
     * @method  所有组及所有的规则
     * @version
     * @User: bevan
     * @param $all_groups
     * @return
     */
    public function allRules($all_groups)
    {

        foreach ($all_groups as &$group) {
            $rules = $group['rules'];

            $rule_arr = explode(',', $rules);

            $all_rules = $this->checkAllRules($rule_arr);

            //获取所有在该规则中的规则
//            $group['rules'] = AuthRuleModel::whereIn('id', $rule_arr)->select();
            $group['rules'] = $all_rules;
        }

        return $all_groups;
    }


    /**
     *
     * @method 权限组规则选中判断
     * @version
     * @User: bevan
     * @param $rule_arr
     * @return
     */
    protected function checkAllRules($rule_arr,$ischeck = false)
    {
        $all_rules = AuthRuleModel::all();

        foreach ($all_rules as $key=>&$rule) {
            if (in_array($rule['id'], $rule_arr)) {
                $rule['checked'] = 1;
            } else {
                if($ischeck == false){
                    $rule['checked'] = 0;
                }else{
                    unset($all_rules[$key]);
                }
            }
        }
        return $all_rules;
    }
}